package com.pro.addresslist.ui.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.bll.FriendshipBLL;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.SortModel;
import com.pro.addresslist.dal.model.V_FriendBean;
import com.pro.addresslist.ui.adapter.PinnedHeaderExpandableAdapter;
import com.pro.addresslist.ui.common.BaseActivity;
import com.pro.addresslist.ui.view.FindEditText;
import com.pro.addresslist.ui.view.PinnedHeaderExpandableListView;

public class FriendActivity extends BaseActivity {
	private PinnedHeaderExpandableListView explistview;
	private List<List<String>> childrenData;
	private List<List<String>> childrenContactID;
	private List<String> groupData;
	private int expandFlag = -1;// 控制列表的展开
	private PinnedHeaderExpandableAdapter adapter;
	private FindEditText searchEtText;
	private List<ContactInfo> list = new ArrayList<ContactInfo>();
	private List<V_FriendBean> childlist = new ArrayList<V_FriendBean>();
	private int grouplength, childtimes = 0;
	
	private static final int ITEM_DELETE = 1;
	private int GroupPosition=-1,ChildPosition=-1;

	/*
	 * private String contactId; private int whichI;
	 */

	@Override
	public int getLayout() {
		return R.layout.activity_friend;

	}

	public class ReceiveBroadCast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("lbs_SelectContactByName")) {
				// 得到广播中得到的数据，并显示出来
				List<ContactInfo> parameter = (List<ContactInfo>) intent
						.getSerializableExtra("parameter");
				list = parameter;
				Log.i("libs", list.size() + "");
				grouplength = list.size();
				if (groupData == null) {
					groupData = new ArrayList<String>();
				}
				for (int i = 0; i < list.size(); i++) {
					groupData.add(i, list.get(i).get_Name());
					FriendshipBLL.SelectFriendShipView(getApplicationContext(),
							list.get(i).get_ContactID());
				}

			}
			if (action.equals("V_SelectFriendShip")) {

				List<V_FriendBean> parameter = (List<V_FriendBean>) intent
						.getSerializableExtra("parameter");
				String conid = (String) intent
						.getSerializableExtra("contactID");

				childlist = parameter;
				Log.i("libs", list.size() + "V_SelectFriendShip");
				if (childrenData == null) {
					childrenData = new ArrayList<List<String>>();
				}
				if (childrenContactID == null) {
					childrenContactID = new ArrayList<List<String>>();
				}

				List<String> item = new ArrayList<String>();
				List<String> itemContactID = new ArrayList<String>();
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).get_ContactID().equals(conid)) {
						for (int j = 0; j < childlist.size(); j++) {
							item.add(childlist.get(j).get_ContactID() + "," + childlist.get(j).get_Name());
							itemContactID.add(childlist.get(j).get_ContactID());
						}
						childrenData.add(i, item);
						childrenContactID.add(i, itemContactID);
					}
				}

				childtimes++;
				if (childtimes == grouplength) {
					Log.i("libs", list.size() + "V_SelectFriendShip＋adapter");

					adapter = new PinnedHeaderExpandableAdapter(childrenData,
							groupData, getApplicationContext(), explistview);
					explistview.setAdapter(adapter);
					disMissDialog();
					adapter.notifyDataSetChanged();
					childtimes = 0;// 查询之后重新置为0
				}
			}
			
			if (action.equals("DeleteFriendShip")) {
				String result = (String) intent.getSerializableExtra("result");
				if (result.equals("succeed")) {
					Toast.makeText(mContext, "删除成功！！", Toast.LENGTH_SHORT)
							.show();
					childrenData.get(GroupPosition).remove(ChildPosition);
					adapter.notifyDataSetChanged();
				} else {
					Toast.makeText(mContext, "删除失败！！", Toast.LENGTH_SHORT)
							.show();

				}
			}
		}

	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {

		setTtile("联系人");
		setLeftImageBack();

		initView();
		initData();

		ReceiveBroadCast receiveBroadCast = new ReceiveBroadCast();
		IntentFilter filter = new IntentFilter();
		filter.addAction("lbs_SelectContactByName");
		filter.addAction("V_SelectFriendShip");
		filter.addAction("DeleteFriendShip");
		registerReceiver(receiveBroadCast, filter);
		
	}

	/**
	 * 初始化VIEW
	 */
	private void initView() {
		explistview = (PinnedHeaderExpandableListView) findViewById(R.id.explistview);

		searchEtText = (FindEditText) findViewById(R.id.filter_edit);
		searchEtText.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					// 先隐藏键盘
					((InputMethodManager) searchEtText.getContext()
							.getSystemService(Context.INPUT_METHOD_SERVICE))
							.hideSoftInputFromWindow(

							getCurrentFocus().getWindowToken(),
									InputMethodManager.HIDE_NOT_ALWAYS);
					// 查询联系人
					clearData();// 清除数据
					String name = searchEtText.getText().toString();
					if (name.isEmpty()) {
						Toast.makeText(FriendActivity.this, "请输入要查找的姓名",
								Toast.LENGTH_SHORT).show();
					} else {
						showProgressDialog();
						ContactInfoBLL.SelectContactByName(
								getApplicationContext(), name);
					}
					return true;
				}
				return false;
			}

			private void clearData() {
				if (groupData.size() != 0) {
					groupData.clear();
				}
				if (childrenData.size() != 0) {
					childrenData.clear();
				}
				if (childrenContactID != null) {
					childrenContactID.clear();
				}
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		groupData = new ArrayList<String>();
		childrenData = new ArrayList<List<String>>();

		// 设置悬浮头部VIEW
		explistview.setHeaderView(getLayoutInflater().inflate(
				R.layout.group_head, explistview, false));
		adapter = new PinnedHeaderExpandableAdapter(childrenData, groupData,
				getApplicationContext(), explistview);
		explistview.setAdapter(adapter);

		// 设置子项点击事件
		explistview.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {

				Intent intent = new Intent(FriendActivity.this,
						PersonalInformationActivity.class);
				intent.putExtra("ContactID",
						childrenContactID.get(groupPosition).get(childPosition));
				startActivity(intent);
				return false;
			}
		});
		
		// 设置长按时的事件
		registerForContextMenu(explistview);
	}
	
	// 长按出现的菜单
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			menu.add(0, ITEM_DELETE, 1, "删除");
		}
		
		@Override
		public boolean onContextItemSelected(MenuItem item) {
			ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item
					.getMenuInfo();

			int type = ExpandableListView
					.getPackedPositionType(info.packedPosition);
			GroupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			// 子条目
			if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
				String childId = ((TextView) info.targetView
						.findViewById(R.id.childid)).getText().toString().trim();
				ChildPosition = (int) info.packedPosition;
				switch (item.getItemId()) {
				case ITEM_DELETE:
					//Toast.makeText(this, "删除" + childId, Toast.LENGTH_SHORT).show();
					FriendshipBLL.DeleteFriendShip(getApplicationContext(), childId);
					break;
				default:
					return false;
				}
				return true;
				// 组
			}

			return true;
		}

	class GroupClickListener implements OnGroupClickListener {
		@Override
		public boolean onGroupClick(ExpandableListView parent, View v,
				int groupPosition, long id) {
			if (expandFlag == -1) {
				// 展开被选的group
				explistview.expandGroup(groupPosition);
				// 设置被选中的group置于顶端
				explistview.setSelectedGroup(groupPosition);
				expandFlag = groupPosition;
			} else if (expandFlag == groupPosition) {
				explistview.collapseGroup(expandFlag);
				expandFlag = -1;
			} else {
				explistview.collapseGroup(expandFlag);
				// 展开被选的group
				explistview.expandGroup(groupPosition);
				// 设置被选中的group置于顶端
				explistview.setSelectedGroup(groupPosition);
				expandFlag = groupPosition;
			}
			return true;
		}

	}

	/**
	 * 为ExpandableListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<ContactInfo> date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();

		for (int i = 0; i < date.size(); i++) {
			SortModel sortModel = new SortModel();
			sortModel.setName(date.get(i).get_Name());
			sortModel.setId(date.get(i).get_ContactID());
			Log.i("libs", date.get(i).get_Name());

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	@Override
	public void OnViewClick(View v) {
		switch (v.getId()) {
		case R.id.btnSave:

			break;
		default:
			break;
		}

	}
}
